#include <QtWidgets/QtWidgets>
#include "playerWindow.h"
#include "songdelegate.h"

#include "QWidgetsContainer.h"

playerWindow::playerWindow(QWidget *parent)
: QMainWindow(parent)
{
	ui.setupUi(this);
	_st = new QSongTaste(this);

	_mediaPlayer = new QMediaPlayer(this);


	connect(_mediaPlayer, &QMediaPlayer::positionChanged, [=](quint64 pos){

		qDebug() << "positionChanged " << pos;

		ui.position->setValue((float)pos / _mediaPlayer->duration() * 100);
	});
	connect(_mediaPlayer, &QMediaPlayer::durationChanged, [=](quint64 duration){

		qDebug() << "durationChanged " << duration;
	});
	connect(_mediaPlayer, &QMediaPlayer::mediaStatusChanged, [=](QMediaPlayer::MediaStatus status){
		if (status==QMediaPlayer::MediaStatus::EndOfMedia)
		{
			nextSong();
		}
	});


	QWidgetsContainer* wc = new QWidgetsContainer(ui.playlistPanel);
	ui.listLayout->addWidget(wc);


	auto recommendSongWidget = new QTreeWidget();
	{
		recommendSongWidget->setItemDelegate(new SongDelegate(recommendSongWidget, this));


		auto head = recommendSongWidget->headerItem();
		{
			head->setText(0, tr("playing"));
			head->setText(1, tr("title"));
		}

		recommendSongWidget->header()->setSectionsMovable(false);
		recommendSongWidget->setIndentation(10);
		recommendSongWidget->setColumnWidth(0, 40);
		connect(recommendSongWidget, &QTreeWidget::itemSelectionChanged, [=]{
			recommendSongWidget->doItemsLayout();
		});
	

		connect(recommendSongWidget, &QTreeWidget::itemDoubleClicked, [=](QTreeWidgetItem* item){

			auto songData = item->data(0, SongDelegate::SongData).value<SongItem>();
			auto songDisplayData = item->data(0, SongDelegate::SongDisplayData).value<SongItemDisplay>();
			this->play(songData);
			//auto download = _st->downloadSong(songData);
			//connect(download, &SongDownload::downloadSongProgress, [=](qint64 bytesReceived, qint64 bytesTotal)mutable{
			//	songDisplayData.setProcess((float)bytesReceived / bytesTotal * 100);
			//	songDisplayData._state = SongItemDisplay::DOWNLOADING;
			//	item->setData(0, SongDelegate::SongDisplayData, QVariant::fromValue(songDisplayData));
			//});
			//connect(download, &SongDownload::downloadSongFinished, [=]{
			//	download->deleteLater();
			//	if (!download->isValid())
			//	{
			//		return;
			//	}
			//	auto&& data=download->getData();
			//	auto path=QDir::tempPath();
			//	auto fileName = path+QDir::separator()+download->getSongItem().getTitle() + download->getSongItem().getSongExt();
			//	QFile songfile(fileName);
			//	if (songfile.open(QFile::WriteOnly))
			//	{
			//		songfile.write(data);
			//		songfile.close();
			//	}
			//});
		});
	}


	//////////////////////////////////////////////////////////////////////////
	auto FavSongWidget = new QTreeWidget();
	{
		FavSongWidget->setItemDelegate(new SongDelegate(FavSongWidget, this));

		auto head = FavSongWidget->headerItem();
		{
			head->setText(0, tr("playing"));
			head->setText(1, tr("title"));
		}

		FavSongWidget->header()->setSectionsMovable(false);
		//recommendSongWidget->header()->setStretchLastSection(false);
		FavSongWidget->setIndentation(10);
		FavSongWidget->setColumnWidth(0, 40);
		//recommendSongWidget->header()->resizeSection(0, 40);
		connect(FavSongWidget, &QTreeWidget::itemSelectionChanged, [=]{
			FavSongWidget->doItemsLayout();
		});
		connect(FavSongWidget, &QTreeWidget::itemDoubleClicked, [=](QTreeWidgetItem* item){

			auto songData = item->data(0, SongDelegate::SongData).value<SongItem>();
			auto songDisplayData = item->data(0, SongDelegate::SongDisplayData).value<SongItemDisplay>();
			this->play(songData);
		});

	}


	//////////////////////////////////////////////////////////////////////////
	wc->addWidget(recommendSongWidget);
	wc->addWidget(FavSongWidget);
	wc->setCurrent(recommendSongWidget);
	_currentWidget = recommendSongWidget;

	connect(ui.btn_refresh, &QPushButton::clicked, [=]{

		auto sl = _st->getRecommendSongList();
		recommendSongWidget->clear();

		for(auto& s : sl)
		{
			QTreeWidgetItem* is = new QTreeWidgetItem();
			is->setData(0, SongDelegate::SongData, QVariant::fromValue(s));
			is->setData(0, SongDelegate::SongDisplayData, QVariant::fromValue(SongItemDisplay{ s.getTitle() }));
			recommendSongWidget->addTopLevelItem(is);

		}
		if (!sl.empty())
		{
			_currentSong = sl.front();
		}
		recommendSongWidget->resizeColumnToContents(1);
		recommendSongWidget->update();

		//////////////////////////////////////////////////////////////////////////
		sl = _st->getFavouriteSongList();
		FavSongWidget->clear();

		for(auto& s : sl)
		{
			QTreeWidgetItem* is = new QTreeWidgetItem();
			is->setData(0, SongDelegate::SongData, QVariant::fromValue(s));
			is->setData(0, SongDelegate::SongDisplayData, QVariant::fromValue(SongItemDisplay{ s.getTitle() }));
			FavSongWidget->addTopLevelItem(is);
		}

		FavSongWidget->resizeColumnToContents(1);
		FavSongWidget->update();

	});

	connect(ui.btn_Stop, &QPushButton::clicked, [=]{
		stop();
	});
	connect(ui.btn_playOrPause, &QPushButton::clicked, [=]{
		if(_mediaPlayer->state() != QMediaPlayer::State::PlayingState)
		{
			if (_mediaPlayer->currentMedia().isNull())
			{
				play(_currentSong);
			}
			else
			{
				play({});
			}
		}
		else
		{
			pause();
		}
	});

	connect(ui.btn_next, &QPushButton::clicked, [=]{
		nextSong();
	});

	connect(ui.btn_RecommendSongList, &QPushButton::clicked, [=]{

		wc->transition(recommendSongWidget);
		_currentWidget = recommendSongWidget;
	});
	connect(ui.btn_FavouriteSongList, &QPushButton::clicked, [=]{

		wc->transition(FavSongWidget);
		_currentWidget = FavSongWidget;
	});


	connect(_st, &QSongTaste::signInSuccessed, [=]
	{
		ui.label->setPixmap(_st->getUserIcon());

	});

	//_st->signIn("", "");




	auto timer = new QTimer(this);

	connect(timer, &QTimer::timeout, [=]{
		auto w = qobject_cast<QTreeWidget*>(wc->getCurrent());
		auto model = w->model();
		for(int r = 0; r < model->rowCount(); r++)
		{
			for(int c = 0; c < model->columnCount(); c++)
			{
				w->update(model->index(r, c));
			}
		}

	});

	timer->start(20);



}

playerWindow::~playerWindow()
{

}

void playerWindow::play(SongItem const& si)
{

	if(si.isValid())
	{	
		_currentSong = si;
		_mediaPlayer->setMedia(_st->getSongFileTmpUrl(si));
	}

	for(int i = 0; i < _currentWidget->topLevelItemCount(); i++)
	{
		auto sd = _currentWidget->topLevelItem(i)->data(0, SongDelegate::SongData).value<SongItem>();

		auto sdd = _currentWidget->topLevelItem(i)->data(0, SongDelegate::SongDisplayData).value<SongItemDisplay>();

		if(sd != _currentSong)
		{
			sdd._playState = SongItemDisplay::STOP;
		}
		else
		{
			sdd._playState = SongItemDisplay::PLAYING;
		}
		_currentWidget->topLevelItem(i)->setData(0, SongDelegate::SongDisplayData, QVariant::fromValue(sdd));
	}

	_mediaPlayer->play();
}

void playerWindow::pause()
{
	_mediaPlayer->pause();
}

void playerWindow::stop()
{
	_mediaPlayer->stop();
}

void playerWindow::nextSong()
{
	int index = 0;
	for(int i = 0; i < _currentWidget->topLevelItemCount(); i++)
	{
		auto sd = _currentWidget->topLevelItem(i)->data(0, SongDelegate::SongData).value<SongItem>();

		auto sdd = _currentWidget->topLevelItem(i)->data(0, SongDelegate::SongDisplayData).value<SongItemDisplay>();

		if(sd != _currentSong)
		{
			sdd._playState = SongItemDisplay::STOP;
		}
		else
		{
			sdd._playState = SongItemDisplay::PLAYING;
			index = i;
		}
		_currentWidget->topLevelItem(i)->setData(0, SongDelegate::SongDisplayData, QVariant::fromValue(sdd));
	}
	SongItem sd;
	if(_currentWidget->topLevelItemCount() > 0)
	{
		sd = _currentWidget->topLevelItem((index + 1) % _currentWidget->topLevelItemCount())->data(0, SongDelegate::SongData).value<SongItem>();
	}
	play(sd);
}

void playerWindow::prevSong()
{

}
